package 华为;

import java.util.Scanner;

/**
 * @author zhangmin
 * @create 2022-08-31 19:27
 */
public class HuaWei_0831_2 {
    static long res=Integer.MAX_VALUE;
    static boolean[][] visited;
    static void backtrack(int[][] matrix,int row,int col,int path,boolean isFrom6){
        int n=matrix.length,m=matrix[0].length;
        if (row<0||row>=n||col<0||col>=m||visited[row][col]) return;
        int cur=matrix[row][col];
        if (cur==3) {
            //到达终点
            res=Math.min(path,res);
            return;
        }
        if (cur==1&&!isFrom6) return;
        visited[row][col]=true;
        int count=1;
        if (cur==4) {
            count=3;
        }
        isFrom6=false;
        if (cur==6){
            isFrom6=true;
        }
        backtrack(matrix,row+1,col,path+count,isFrom6);
        backtrack(matrix,row-1,col,path+count,isFrom6);
        backtrack(matrix,row,col+1,path+count,isFrom6);
        backtrack(matrix,row,col-1,path+count,isFrom6);
        visited[row][col]=false;
    }

    public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        int n=cin.nextInt();
        int m=cin.nextInt();
        visited=new boolean[n][m];
        int[][] matrix=new int[n][m];
        int start_i=-1,start_j=-1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j]=cin.nextInt();
                if (matrix[i][j]==2){
                    start_i=i;
                    start_j=j;
                }
            }
        }
        backtrack(matrix,start_i,start_j,0,false);
        System.out.println(res);
    }

}
